package com.tms.app.tms.ui.login;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.sdk.android.ams.common.util.StringUtil;
import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.CommonCallback;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.code19.library.VerificationUtils;
import com.google.gson.JsonSyntaxException;
import com.tms.app.tms.R;
import com.tms.app.tms.app.Constant;
import com.tms.app.tms.bean.response.BaseResponse;
import com.tms.app.tms.bean.response.LoginRes;
import com.tms.app.tms.ui.base.presenter.BasePresenter;
import com.tms.app.tms.ui.base.ui.BaseActivity;
import com.tms.app.tms.ui.base.view.IBaseView;
import com.tms.app.tms.ui.home.MainActivity;
import com.tms.app.tms.utils.AES;
import com.tms.app.tms.utils.DeviceUtil;
import com.tms.app.tms.utils.SharePreferenceUtil;
import com.tms.app.tms.utils.TimeUtil;
import com.tms.app.tms.utils.youtu.SystemUtil;
import com.tms.app.tms.widget.MyDialogSelect;

import org.xutils.http.RequestParams;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by happy on 2017/9/1.
 */

public class LoginAt extends BaseActivity implements View.OnClickListener, TimeUtil.TimeDownEvent ,IBaseView{


    @BindView(R.id.text_phone)
    EditText textPhone;
    @BindView(R.id.edit_vcode)
    EditText editVcode;
    @BindView(R.id.button_vcode)
    TextView buttonVcode;
    @BindView(R.id.button_send)
    Button buttonSend;
    private boolean flagTime=true;
    BasePresenter presenter;
    CloudPushService pushService = PushServiceFactory.getCloudPushService();
    private int method;
    private String mobile;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_at_login_new);
        ButterKnife.bind(this);
        initView();
        presenter=new BasePresenter();
        presenter.setiView(this);
        int type=getIntent().getIntExtra("type",0);
        if (type==1){
            autoLogin();
        }

    }


    private void initView() {
        textPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length()>0)
                    buttonVcode.setEnabled(true);
                else
                    buttonVcode.setEnabled(false);
            }
        });
        editVcode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length()>0&&textPhone.getText().length()>0){
                    buttonSend.setEnabled(true);
                }else {
                    buttonSend.setEnabled(false);
                }
            }
        });
    }


    @OnClick({R.id.button_vcode,R.id.button_send,R.id.register})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button_vcode:
                    getVcode();
                break;
            case R.id.button_send:
                doLogin();
                break;
            case R.id.register:
                myDialogSelect = new MyDialogSelect(this, this, "", "");
                myDialogSelect.show();
                break;
            case R.id.dialog_button_2:
                myDialogSelect.close();
                callPhone("123-456-789");
                break;
            case R.id.dialog_button_1:
                myDialogSelect.close();
        }
    }
    private void autoLogin() {
        if ((System.currentTimeMillis() - mExitTime) < 2000) {
            mExitTime = System.currentTimeMillis();
            return;
        }
        method=2;
        RequestParams params=new RequestParams(Constant.AUTO_LOGIN);
        params.addBodyParameter("token", SharePreferenceUtil.getString(this,"token",""));
        presenter.getObjectFromServer(params);
        showLoadingDialog();
    }
    private void doLogin() {
        if ((System.currentTimeMillis() - mExitTime) < 2000) {
            mExitTime = System.currentTimeMillis();
            return;
        }
        String mobile=textPhone.getText().toString().replace(" ","");
        if (!VerificationUtils.matcherPhoneNum(mobile)){
            showMsg("请输入正确手机号");
            return;
        }
        if (!VerificationUtils.isNumeric(mobile)){
            showMsg("请输入正确手机号");
            return;
        }
        method=1;

        String deviceId=pushService.getDeviceId();
        RequestParams params=new RequestParams(com.tms.app.tms.app.Constant.LOGIN_Mobile);
        params.addBodyParameter("mobile",textPhone.getText().toString());
        params.addBodyParameter("sign", AES.encode(mobile ));
        params.addBodyParameter("code",editVcode.getText().toString());
        params.addBodyParameter("deviceId",deviceId );
        params.addBodyParameter("os","andriod");
        params.addBodyParameter("osVersion", SystemUtil.getSystemVersion());
        params.addBodyParameter("carrierOperator",SystemUtil.getSubscribe(this));
        presenter.getObjectFromServer(params);
        showLoadingDialog();
        clearLocalUserData();
    }

    private void getVcode() {
        if ((System.currentTimeMillis() - mExitTime) < 2000) {
            mExitTime = System.currentTimeMillis();
            return;
        }
        if (!VerificationUtils.matcherPhoneNum(textPhone.getText().toString())){
           showMsg("请输入正确手机号");
            return;
        }
        mobile=textPhone.getText().toString().replace(" ","");
        method=0;
        RequestParams params=new RequestParams(com.tms.app.tms.app.Constant.LOGIN_VCODE);
        params.addBodyParameter("mobile",mobile);
        String sign =AES.encode(mobile );
        params.addBodyParameter("sign",sign );
        presenter.getObjectFromServer(params);
        showLoadingDialog();
    }

    @Override
    public void timeDown(int indexTime) {
        if (indexTime == -1) {
            flagTime = true;
            buttonVcode.setEnabled(true);
            buttonVcode.setText("发送");
            return;
        }

        indexTime = Constant.TIMER - indexTime;
        indexTime = indexTime / 1000;
        buttonVcode.setText(indexTime + "秒后重新发送");
    }

    private  String getDeviceId(){
        String deviceId= SharePreferenceUtil.getString(this,"deviceId","");
        if (deviceId.equals("")){
            deviceId= DeviceUtil.getDeviceId(this);
            SharePreferenceUtil.setValue(this,"deviceId",deviceId);
        }
        return deviceId;
    }

    @Override
    public void bandResultToView(String json) {
        hideLoadingDialog();
        BaseResponse baseResponse=gson.fromJson(json,BaseResponse.class);
        if (baseResponse==null||baseResponse.getCode()!=200){
            if (method==0){
                switch (baseResponse.getCode()){
                    case 4041:
                        showMsg("权限错误");
                        break;
                    case 4042:
                        showMsg("无此用户,请更换号码");
                        break;
                    default:
                        showMsg("发送失败");
                }
            }

            if (method==1)
                showMsg("登录失败");
            return;
        }
        if (method==0){
            TimeUtil.timeDown(Constant.TIMER, this);
            buttonVcode.setEnabled(false);
            showMsg("验证码已发送到手机"+textPhone.getText().toString());
            return;
        }
        if (StringUtil.isEmpty(mobile)){
            mobile=SharePreferenceUtil.getString(this,"mobile","");
        }
        pushService.bindAccount(textPhone.getText().toString(), new CommonCallback() {
            @Override
            public void onSuccess(String s) {
                    System.out.print("绑定帐号成功"+s);
            }

            @Override
            public void onFailed(String s, String s1) {
                System.out.print("绑定帐号失败"+s);
            }
        });
            startActivity(new Intent(this,MainActivity.class));
        try {
            LoginRes loginRes=gson.fromJson(json,LoginRes.class);
            SharePreferenceUtil.setValue(this,"token",loginRes.getData().getToken());
            SharePreferenceUtil.setValue(this,"mobile",mobile);
            finish();
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
        }

    }
}
